from flask import current_app
from flask import request, jsonify, session
from first_info.models import User, News, Category
from first_info import response_code, db, constants
from . import user_blue
from flask import render_template, g, redirect, url_for
from first_info.utils.comment import user_login_data
from first_info.utils.file_storage import upload_file


# 新闻列表显示，只有get方法
@user_blue.route('/news_list')
@user_login_data
def news_list():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))

    p = request.args.get('p', '1')
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = "1"
    paginate = None
    total_page = 1
    current_page = 1
    try:
        paginate = user.news_list.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)
    news_lists = []
    try:
        news_lists = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)

    news_list_dict = []
    for news in news_lists:
        news_list_dict.append(news.to_review_dict())
    data = {
        'news_list': news_list_dict,
        'total_page': total_page,
        'current_page': current_page
    }
    return render_template('news/user_news_list.html', **data)

# 发布新闻
@user_blue.route('/news_release', methods=['GET', 'POST'])
@user_login_data
def news_release():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    if request.method == 'GET':
        category_list = []
        try:
            category_list = Category.query.filter(Category.id != 1).all()
        except Exception as e:
            current_app.logger.error(e)
        data = {
            'category_list': category_list
        }
        return render_template('news/user_news_release.html', **data)
    if request.method == 'POST':

    # 1.接收参数
        title = request.form.get('title')
        source = '个人发布'
        category_id = request.form.get('category_id')
        digest = request.form.get('digest')
        index_image = request.files.get('index_image')
        content = request.form.get('content')
        # 2.校验参数
        if not all([title, source, category_id, digest, index_image, content]):
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数不全')
        try:
            index_image_file = index_image.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数有误')
        try:
            key = upload_file(index_image_file)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.THIRDERR, errmag='七牛云储存错误')

        #  3.创建模型对象
        news = News()
        news.title = title
        news.source = source
        news.digest = digest
        news.content = content
        news.index_image_url = constants.QINIU_DOMIN_PREFIX+key
        news.category_id = category_id
        news.user_id = user.id
        news.status = 1
        try:
            db.session.add(news)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DBERR, errmag='新闻存储失败')
        # 响应存储结果
        return jsonify(errno=response_code.RET.OK, errmag='新闻存储成功')


# 显示用户收藏的新闻
@user_blue.route('/collection')
@user_login_data
def user_collection():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    # 1.获取参数 (页数)
    p = request.args.get("p", "1")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = "1"
    paginate = None
    items = []
    total_pages = 1
    current_page = 1
    try:
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
    except Exception as e:
        current_app.logger.error(e)
    if paginate:
        items = paginate.items  # 所有新闻
        total_pages = paginate.pages  # 多少页
        current_page = paginate.page  # 当前第几页

    collection_news = []
    for item in items:
        collection_news.append(item.to_basic_dict())

    data = {
        "news_list": collection_news,
        "total_pages": total_pages,
        "current_page": current_page

    }
    return render_template("news/user_collection.html", **data)


# 修改密码
@user_blue.route('/pass_info', methods=['GET', 'POST'])
@user_login_data
def pass_info():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    if request.method == 'POST':
        # 1.获取参数
        old_password = request.json.get('old_password')
        new_password = request.json.get('new_password')
        # 2.校验参数
        if not all([old_password, new_password]):
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数有误')
        user_id = user.check_password(old_password)
        if not user_id:
            return jsonify(errno=response_code.RET.PWDERR, errmag='密码输入错误')
        #  3.更新数据库密码
        user.password =new_password
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DBERR, errmag='修改密码失败')
        return jsonify(errno=response_code.RET.OK, errmag='修改成功')




# 修改头像页面
@user_blue.route('/pic_info', methods=['GET', 'POST'])
@user_login_data
def pic_info():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_pic_info.html', **data)
    if request.method == 'POST':
        # 1.接收参数
        avatar = request.files.get('avatar')
        try:
            avatar_file = avatar.read()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.PARAMERR, errmag='头像上传失败')
        try:
            key = upload_file(avatar_file)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=response_code.RET.THIRDERR, errmag='七牛云保存失败')
        user.avatar_url = key
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET, errmag='上传头像失败')

        data = {
            "avatar_url": constants.QINIU_DOMIN_PREFIX + key
        }
        return jsonify(errno=response_code.RET.OK, errmag='上传成功', **data)


# 基本信息页面
@user_blue.route('/base_info', methods=['GET', 'POST'])
@user_login_data
def base_info():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))
    if request.method == "GET":
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', **data)
    if request.method == "POST":
        # 1.接收参数
        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')
        # 2.校验参数
        if not all([nick_name, signature, gender]):
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数不全')
        # 2.1 校验性别是否在MAN，WOMAN中
        if gender not in ('MAN', 'WOMAN'):
            return jsonify(errno=response_code.RET.PARAMERR, errmag='参数错误')
        # 2.2 校验个性昵称是否重复
        # nick_names = User.query.filter(User.nick_name == nick_name, User.id != user.id).first()
        # if nick_names:
        #     return jsonify(errno=response_code.RET.PARAMERR, errmag='昵称重复')
        # 3.查询数据库
        user.nick_name = nick_name
        user.signature = signature
        user.gender = gender
        try:
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=response_code.RET.DBERR, errmag='修改失败')
        # 3.1 修改session中存储的nick_name
        session['nick_name'] = nick_name
        # 4.响应正常结果
        return jsonify(errno=response_code.RET.OK, errmag='操作成功')

# 主页面
@user_blue.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect(url_for('index.index'))

    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', **data)
